<!-- 左侧通用菜单组件 -->
<script lang="ts" setup>
import type { MenuMixedOption } from 'naive-ui/es/menu/src/interface'
import { menuOptions } from '@/mock/json/menuOptions'

const router = useRouter()
const route = useRoute()
const selectedKey = ref<string | null>(null)

// 将自定义菜单数据转换为naiveUI所需要的格式
const convertedMenuOptions = computed<MenuMixedOption[]>(() =>
  menuOptions.map(item => ({
    label: item.MenuName,
    key: item.path,
    icon: typeof item.icon === 'function' ? item.icon : undefined,
    additional: { id: item.id },
  })),
)

const handlerNavigation = (key: string) => {
  router.push(key)
}

// 监听当前路有变化，动态更新selectedKey
watch(
  () => route.path,
  (newPath) => {
    selectedKey.value = newPath
  },
  { immediate: true },
)

// 页面加载时初始化selectedKey
onMounted(() => {
  selectedKey.value = route.path
})
</script>

<template>
  <n-menu
    v-model:value="selectedKey"
    :options="convertedMenuOptions"
    accordion
    @update:value="handlerNavigation"
  />
</template>

<style scoped></style>
